package org.jetlinks.pro.clickhouse.metadata;

import lombok.Getter;
import lombok.Setter;
import org.hswebframework.ezorm.core.DefaultValue;
import org.hswebframework.ezorm.rdb.executor.DefaultBatchSqlRequest;
import org.hswebframework.ezorm.rdb.executor.SqlRequest;
import org.hswebframework.ezorm.rdb.metadata.RDBColumnMetadata;
import org.hswebframework.ezorm.rdb.metadata.RDBIndexMetadata;
import org.hswebframework.ezorm.rdb.metadata.RDBTableMetadata;
import org.hswebframework.ezorm.rdb.metadata.dialect.DataTypeBuilder;
import org.hswebframework.ezorm.rdb.operator.builder.fragments.NativeSql;
import org.hswebframework.ezorm.rdb.operator.builder.fragments.PrepareSqlFragments;
import org.hswebframework.ezorm.rdb.operator.builder.fragments.ddl.CreateIndexParameter;
import org.hswebframework.ezorm.rdb.operator.builder.fragments.ddl.CreateIndexSqlBuilder;
import org.hswebframework.ezorm.rdb.operator.builder.fragments.ddl.CreateTableSqlBuilder;
import org.jetlinks.pro.clickhouse.engine.Engine;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.StringJoiner;

@SuppressWarnings("all")
@Getter
@Setter
public class ClickHouseCreateTableSqlBuilder implements CreateTableSqlBuilder {

    @Override
    public SqlRequest build(RDBTableMetadata table) {
        DefaultBatchSqlRequest sql = new DefaultBatchSqlRequest();

        List<String> columns = new ArrayList<>(table.getColumns().size());


        int index = 0;
        for (RDBColumnMetadata column : table.getColumns()) {

            DataTypeBuilder typeBuilder = ((DataTypeBuilder) column.getType());

            StringJoiner columnDef = new StringJoiner(" ");
            columnDef.add(column.getName())
                     .add(typeBuilder.createColumnDataType(column));
            if (StringUtils.hasText(column.getComment())) {
                columnDef.add("comment '" + column.getComment() + "'");
            }

            columns.add(columnDef.toString());

        }

        sql.setSql(table.findFeatureNow(Engine.ID)
                        .buildCreateTableSql(table.getName(), columns.toArray(new String[0])));

        return sql;
    }

}
